package com.gitee.l0km.aocache;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import com.gitee.l0km.aocache.exception.AocacleError;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkArgument;

/**
 * {@link InvocationHandler} for an {@link Annotation} that Spring has
 * <em>synthesized</em> (i.e. wrapped in a dynamic proxy) with additional
 * functionality such as attribute alias handling.
 *
 * @param <A> the annotation type
 * @author guyadong
 */
final class SynthesizedAnnotationInvocationHandler<A extends Annotation> implements InvocationHandler {

	private final Class<A> annotationType;

	private final AnnotationAttributes attributes;
	

	private volatile Integer hashCode;
	private volatile String string;

	private final Method[] attributeMethods;


	private SynthesizedAnnotationInvocationHandler(AnnotationAttributes attributes, Class<A> annotationType) {
		checkNotNull(annotationType, "annotationType must not be null");
		checkArgument(annotationType.isAnnotation(), "Type must be an annotation");
		this.attributes = new AnnotationAttributes(checkNotNull(attributes,"attributes is null"),annotationType,false);
		this.annotationType = annotationType;
		this.attributeMethods = compute(annotationType);
	}
	@SuppressWarnings("unchecked")
	private SynthesizedAnnotationInvocationHandler(AnnotationAttributes attributes) {
		this(attributes, (Class<A>) checkNotNull(attributes,"attributes is null").annotationType());
	}


	@Override
	public Object invoke(Object proxy, Method method, Object[] args) {
		if (isEqualsMethod(method)) {
			return annotationEquals(args[0]);
		}
		if (isHashCodeMethod(method)) {
			return annotationHashCode();
		}
		if (isToStringMethod(method)) {
			return annotationToString();
		}
		if (isAnnotationTypeMethod(method)) {
			return this.annotationType;
		}
		if (indexOf(method.getName()) != -1) {
			return getAttributeValue(method);
		}
		throw new AocacleError(String.format(
				"Method [%s] is unsupported for synthesized annotation type [%s]", method, this.annotationType.getName()));
	}

	private boolean isAnnotationTypeMethod(Method method) {
		return (method.getName().equals("annotationType") && method.getParameterTypes().length == 0);
	}

	/**
	 * See {@link Annotation#equals(Object)} for a definition of the required algorithm.
	 * @param other the other object to compare against
	 */
	private boolean annotationEquals(Object other) {
		if (this == other) {
			return true;
		}
		if (!this.annotationType.isInstance(other)) {
			return false;
		}
		for (int i = 0; i < this.attributeMethods.length; i++) {
			Method attribute = this.attributeMethods[i];
			Object thisValue = getAttributeValue(attribute);
			Object otherValue = invokeMethod(attribute, other);
			if (!ObjectUtils.nullSafeEquals(thisValue, otherValue)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * See {@link Annotation#hashCode()} for a definition of the required algorithm.
	 */
	private int annotationHashCode() {
		Integer hashCode = this.hashCode;
		if (hashCode == null) {
			hashCode = computeHashCode();
			this.hashCode = hashCode;
		}
		return hashCode;
	}

	private Integer computeHashCode() {
		int hashCode = 0;
		for (int i = 0; i < this.attributeMethods.length; i++) {
			Method attribute = this.attributeMethods[i];
			Object value = getAttributeValue(attribute);
			hashCode += (127 * attribute.getName().hashCode()) ^ getValueHashCode(value);
		}
		return hashCode;
	}

	private int getValueHashCode(Object value) {
		// Use Arrays.hashCode(...) since Spring's ObjectUtils doesn't comply
		// with the requirements specified in Annotation#hashCode().
		if (value instanceof boolean[]) {
			return Arrays.hashCode((boolean[]) value);
		}
		if (value instanceof byte[]) {
			return Arrays.hashCode((byte[]) value);
		}
		if (value instanceof char[]) {
			return Arrays.hashCode((char[]) value);
		}
		if (value instanceof double[]) {
			return Arrays.hashCode((double[]) value);
		}
		if (value instanceof float[]) {
			return Arrays.hashCode((float[]) value);
		}
		if (value instanceof int[]) {
			return Arrays.hashCode((int[]) value);
		}
		if (value instanceof long[]) {
			return Arrays.hashCode((long[]) value);
		}
		if (value instanceof short[]) {
			return Arrays.hashCode((short[]) value);
		}
		if (value instanceof Object[]) {
			return Arrays.hashCode((Object[]) value);
		}
		return value.hashCode();
	}

	private String annotationToString() {
		String string = this.string;
		if (string == null) {
			StringBuilder builder = new StringBuilder("@").append(this.annotationType.getName()).append('(');
			for (int i = 0; i < this.attributeMethods.length; i++) {
				Method attribute = this.attributeMethods[i];
				if (i > 0) {
					builder.append(", ");
				}
				builder.append(attribute.getName());
				builder.append('=');
				builder.append(toString(getAttributeValue(attribute)));
			}
			builder.append(')');
			string = builder.toString();
			this.string = string;
		}
		return string;
	}

	private String toString(Object value) {
		if (value instanceof Class) {
			return ((Class<?>) value).getName();
		}
		if (value.getClass().isArray()) {
			StringBuilder builder = new StringBuilder("[");
			for (int i = 0; i < Array.getLength(value); i++) {
				if (i > 0) {
					builder.append(", ");
				}
				builder.append(toString(Array.get(value, i)));
			}
			builder.append(']');
			return builder.toString();
		}
		return String.valueOf(value);
	}
	private Object getAttributeValue(Method method) {
		Object value = attributes.readValidValueOf(method);

		// Clone non-empty arrays so that users cannot alter the contents of values in our cache.
		if (value.getClass().isArray() && Array.getLength(value) > 0) {
			value = cloneArray(value);
		}

		return value;
	}

	/**
	 * Clone the provided array, ensuring that the original component type is retained.
	 * @param array the array to clone
	 */
	private Object cloneArray(Object array) {
		if (array instanceof boolean[]) {
			return ((boolean[]) array).clone();
		}
		if (array instanceof byte[]) {
			return ((byte[]) array).clone();
		}
		if (array instanceof char[]) {
			return ((char[]) array).clone();
		}
		if (array instanceof double[]) {
			return ((double[]) array).clone();
		}
		if (array instanceof float[]) {
			return ((float[]) array).clone();
		}
		if (array instanceof int[]) {
			return ((int[]) array).clone();
		}
		if (array instanceof long[]) {
			return ((long[]) array).clone();
		}
		if (array instanceof short[]) {
			return ((short[]) array).clone();
		}

		// else
		return ((Object[]) array).clone();
	}

	@SuppressWarnings("unchecked")
	static <A extends Annotation> A createProxy(AnnotationAttributes attributes, Class<A> annotationType) {
		ClassLoader classLoader = annotationType.getClassLoader();
		InvocationHandler handler = new SynthesizedAnnotationInvocationHandler<>(attributes, annotationType);
		Class<?>[] interfaces = new Class<?>[] {annotationType};
		return (A) Proxy.newProxyInstance(classLoader, interfaces, handler);
	}
	@SuppressWarnings("unchecked")
	static <A extends Annotation> A createProxy(AnnotationAttributes attributes) {
		return createProxy(attributes, (Class<A>) checkNotNull(attributes,"attributes is null").annotationType());
	}

	private int indexOf(String name) {
		for(int i = 0; i < attributeMethods.length; ++i) {
			if(attributeMethods[i].getName().equals(name)) {
				return i;
			}
		}
		return -1;
	}
	private static Object invokeMethod(Method method, Object target, Object... args) {
		try {
			return method.invoke(target, args);
		}catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		}
	}
	/**
	 * Determine whether the given method is an "equals" method.
	 * @see java.lang.Object#equals(Object)
	 */
	private static boolean isEqualsMethod(Method method) {
		if (method == null) {
			return false;
		}
		if (method.getParameterTypes().length != 1) {
			return false;
		}
		if (!method.getName().equals("equals")) {
			return false;
		}
		return method.getParameterTypes()[0] == Object.class;
	}
	/**
	 * Determine whether the given method is a "hashCode" method.
	 * @see java.lang.Object#hashCode()
	 */
	private static boolean isHashCodeMethod(Method method) {
		return method != null && method.getParameterTypes().length == 0 && method.getName().equals("hashCode");
	}

	/**
	 * Determine whether the given method is a "toString" method.
	 * @see java.lang.Object#toString()
	 */
	private static boolean isToStringMethod(Method method) {
		return (method != null && method.getParameterTypes().length == 0 && method.getName().equals("toString"));
	}
	private static final Predicate<Method> ATTRIBUTE_METHOD_FILTER = new Predicate<Method>() {
		@Override
		public boolean apply(Method input) {
			return (input.getParameterTypes().length == 0 && input.getReturnType() != void.class);
		}
	};
	private static Method[] compute(Class<? extends Annotation> annotationType) {
		return FluentIterable.from(annotationType.getDeclaredMethods())
				.filter(ATTRIBUTE_METHOD_FILTER)
				.toArray(Method.class);
	}

}
